package com.myrpc.consumer.netty;


import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.PreDestroy;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import com.myrpc.common.MyMessageDecoder;
import com.myrpc.common.MyMessageEncoder;
import com.myrpc.common.sessionchannel.SessionMap;
import com.myrpc.consumer.xml.RpcInterFaceData;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class NettyClient implements InitializingBean{
	
	Bootstrap bootstrap  = new Bootstrap();
	
	EventLoopGroup worker = new NioEventLoopGroup();
	public NettyClient() {
		bootstrap.group(worker);
		try {
		//设置socket工厂类
		bootstrap.channel(NioSocketChannel.class);
		
		bootstrap.handler(new ChannelInitializer<Channel>() {

			@Override
			protected void initChannel(Channel ch) throws Exception {
				
				// 客户端的逻辑
				ch.pipeline().addLast("frameDecoder",new LengthFieldBasedFrameDecoder(65535,0,3,0,3));
//在ByteBuf之前增加2个字节的消息长度字段
				ch.pipeline().addLast("frameEncoder",new LengthFieldPrepender(3));

				ch.pipeline().addLast(new MyMessageEncoder());
				ch.pipeline().addLast(new MyMessageDecoder());
				ch.pipeline().addLast(new ClientHandler());
			}
			
		});
		
	
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	@PreDestroy
	public void destroy() {
		log.info("RPC客户端退出,释放资源!");
		worker.shutdownGracefully();
	}

	
	public Channel connect(String ip,int port) {
	
		try {
			ChannelFuture channelFuture = bootstrap.connect(ip,port).sync();
			System.out.println("client start ....");
			return channelFuture.channel();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		/*
		 * Map<String, String> interfaceDatas = RpcInterFaceData.interfaceDatas;
		 * Iterator<Entry<String, String>> iterator =
		 * interfaceDatas.entrySet().iterator();
		 * 
		 * while(iterator.hasNext()) { Entry<String, String> entry = iterator.next();
		 * Channel channel = connect("127.0.0.1", 10000);
		 * SessionMap.setSession(entry.getValue(), channel, entry.getKey());
		 * 
		 * }
		 * 
		 * 
		 * log.info("session size{}" , SessionMap.size());
		 */
	}

}
